<template>
  <div style="padding: 20px">
    <!-- Tabs - 美化后的现代风格 -->
    <el-tabs
      v-model="activeTab"
      type="card"
      @tab-click="handleTabClick"
      class="modern-tabs"
      style="margin-bottom: 20px"
    >
      <el-tab-pane label="调度" name="scheduling">
        <span slot="label">
          <i class="el-icon-s-operation"></i>
          <span class="tab-text">调度</span>
        </span>
      </el-tab-pane>
      <el-tab-pane label="方式" name="method">
        <span slot="label">
          <i class="el-icon-s-tools"></i>
          <span class="tab-text">方式</span>
        </span>
      </el-tab-pane>
      <el-tab-pane label="水新" name="waterNew">
        <span slot="label">
          <i class="el-icon-s-finance"></i>
          <span class="tab-text">水新</span>
        </span>
      </el-tab-pane>
      <el-tab-pane label="现货" name="spot">
        <span slot="label">
          <i class="el-icon-s-goods"></i>
          <span class="tab-text">现货</span>
        </span>
      </el-tab-pane>
      <el-tab-pane label="自动化" name="automation">
        <span slot="label">
          <i class="el-icon-s-data"></i>
          <span class="tab-text">自动化</span>
        </span>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 新增按钮 -->
    <div style="margin-bottom: 20px; text-align: left">
      <el-button type="primary" icon="el-icon-plus" @click="openAddDialog">
        新增记录
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :data="pagedTableData"
      style="width: 100%"
      border
      v-loading="loading"
    >
      <el-table-column prop="text" label="内容" min-width="500"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
      <el-table-column prop="createdByName" label="创建人" width="120"></el-table-column>
      <el-table-column label="操作" fixed="right" width="180">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-wrapper" style="margin-top: 15px; text-align: right">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 20, 50]"
        :page-size.sync="pageSize"
        :current-page.sync="currentPage"
        :total="totalCounts"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="700px"
      @close="resetForm"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        ref="formRef"
        label-width="80px"
      >
        <el-form-item label="展示文本" prop="text">
          <el-input
            v-model="formData.text"
            type="textarea"
            :rows="8"
            placeholder="请输入内容"
            maxlength="500"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      activeTab: "scheduling",
      loading: false,
      currentPage: 1,
      pageSize: 10,
      totalCounts: 0, // 总条数，用于分页

      tableData: {},
      tabData: {
        scheduling: [],
        method: [],
        waterNew: [],
        spot: [],
        automation: [],
      },
      
      // API请求配置
  apiConfig: {
    list: '/pbgljjbjl/list',
    add: '/pbgljjbjl/add',
    update: '/pbgljjbjl/update',
    delete: '/pbgljjbjl/delete'
  },
  
  // 标签页名称映射
  tabNameMap: {
    scheduling: '调度',
    method: '方式',
    waterNew: '水新',
    spot: '现货',
    automation: '自动化'
  },

      dialogVisible: false,
      isEditing: false,
      editingIndex: -1,
      formData: {
        text: "",
      },
      formRules: {
        text: [
          { required: true, message: "请输入展示文本", trigger: "blur" },
          { max: 500, message: "最多输入500字", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    currentTableData() {
      return this.tabData[this.activeTab] || [];
    },
    pagedTableData() {
      const start = (this.currentPage - 1) * this.pageSize;
      return this.currentTableData.slice(start, start + this.pageSize);
    },
    dialogTitle() {
      return this.isEditing ? "编辑记录" : "新增记录";
    },
  },
  methods: {
    // 获取数据
    fetchData() {
      this.loading = true;
      
      var proxy = {
          url: this.apiConfig.list,
          datas: {
            tabType: this.activeTab,
            category: this.tabNameMap[this.activeTab] || '',
            pageNum: this.currentPage,
            pageSize: this.pageSize
          }
        };
      
      this.$oPost({ proxy }, (response) => {
        this.loading = false;
        
        if (response && response.code === 1000) {
          // 假设后端返回的数据结构是 { list: [], total: 0 }
          // 如果返回的就是数组，则使用原逻辑
          if (Array.isArray(response.data)) {
            this.tabData[this.activeTab] = response.data || [];
          } else {
            this.tabData[this.activeTab] = response.data.list || [];
            // 保存总条数用于分页
            this.totalCounts = response.data.total || 0;
          }
        } else {
          this.$message.error('获取数据失败：' + (response.msg || '未知错误'));
          this.tabData[this.activeTab] = [];
          this.totalCounts = 0;
        }
      }, (error) => {
        this.loading = false;
        this.$message.error('获取数据时发生错误');
        this.tabData[this.activeTab] = [];
        this.totalCounts = 0;
      });
    },
    
    handleTabClick() {
      this.currentPage = 1;
      this.fetchData();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
    },
    handleCurrentChange(val) {
      this.currentPage = val;
    },

    // ✅ 点击“新增记录”弹出窗口
    openAddDialog() {
      this.isEditing = false;
      this.editingIndex = -1;
      this.formData = {
        text: "",
      };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) this.$refs.formRef.clearValidate();
      });
    },

    submitForm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.loading = true;
          
          var proxy = {
              url: this.isEditing ? this.apiConfig.update : this.apiConfig.add,
              datas: {
                ...this.formData,
                tabType: this.activeTab,
                category: this.tabNameMap[this.activeTab] || ''
              }
            };
          
          this.$oPost({ proxy }, (response) => {
            this.loading = false;
            
            if (response && response.code === 1000) {
              this.$message.success(this.isEditing ? "编辑成功" : "新增成功");
              this.dialogVisible = false;
              this.fetchData();
            } else {
              this.$message.error((this.isEditing ? '编辑失败' : '新增失败') + "：" + (response.msg || '未知错误'));
            }
          }, (error) => {
            this.loading = false;
            this.$message.error('提交表单时发生错误');
          });
        }
      });
    },

    handleEdit(row) {
      this.isEditing = true;
      this.editingIndex = this.currentTableData.findIndex((r) => r === row);
      this.formData = { ...row };
      this.dialogVisible = true;
      this.$nextTick(() => {
        if (this.$refs.formRef) this.$refs.formRef.clearValidate();
      });
    },

    handleDelete(row) {
      this.$confirm(`确定删除吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          
          var proxy = {
              url: this.apiConfig.delete,
              datas: {
                id: row.id || row.text, // 使用text作为临时id
                tabType: this.activeTab,
                category: this.tabNameMap[this.activeTab] || ''
              }
            };
          
          this.$oPost({ proxy }, (response) => {
            this.loading = false;
            
            if (response && response.code === 1000) {
              this.$message.success("删除成功");
              this.fetchData();
            } else {
              this.$message.error('删除失败：' + (response.msg || '未知错误'));
            }
          }, (error) => {
            this.loading = false;
            this.$message.error('删除数据时发生错误');
          });
        })
        .catch(() => {});
    },

    resetForm() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
    },
  },
  
  // 组件挂载时获取数据
  mounted() {
    this.fetchData();
  },
};
</script>

<style scoped>
/* 仅美化tab栏样式 */
.modern-tabs >>> .el-tabs__header {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  border-radius: 8px 8px 0 0;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
  margin: 0;
  padding: 0 10px;
}

.modern-tabs >>> .el-tabs__nav {
  height: 48px;
}

.modern-tabs >>> .el-tabs__item {
  height: 48px;
  line-height: 48px;
  padding: 0 20px;
  margin: 0 4px;
  border: none;
  font-weight: 500;
  color: #606266;
  border-radius: 6px 6px 0 0;
  transition: all 0.3s ease;
}

.modern-tabs >>> .el-tabs__item.is-active {
  background: #ffffff;
  color: #409EFF;
  border-bottom: 2px solid #409EFF;
  position: relative;
  top: 1px;
  font-weight: 600;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.15);
}

.modern-tabs >>> .el-tabs__item:hover:not(.is-active) {
  background: #f0f5ff;
  color: #409EFF;
}

.tab-text {
  margin-left: 6px;
}

/* 保留原有的分页器样式 */
.pagination-wrapper {
  margin-top: 15px;
  text-align: right;
}
</style>